package com.zhou.framework.aop.aspect;

import com.alibaba.fastjson.JSON;
import com.zhou.framework.util.SessionUtil;
import com.zhou.util.ObjectUtil;
import com.zhou.util.StringTool;
import com.zhou.util.WebUtil;
import com.zhou.framework.aop.anotation.LogOption;
import com.zhou.framework.aop.enums.LogLevel;
import com.zhou.framework.config.SystemConfig;
import com.zhou.framework.dao.Log;
import com.zhou.framework.filter.PropertyExcludeFilter;
import com.zhou.framework.jwt.model.LoginUser;
import com.zhou.framework.model.RS;
import com.zhou.framework.util.ExceptionUtil;
import com.zhou.framework.util.ThreadPoolManager;
import com.zhou.org.dao.User;
import com.zhou.org.model.LoginResult;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

/**
 * 记录操作日志
 * @author lang.zhou
 * @since 2023/2/18
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    // 开始时间
    private long startTime = 0L;
    // 结束时间
    private long endTime = 0L;
    /** 排除敏感属性字段 */
    public static final String[] EXCLUDE_PARAMETERS = { "password", "oldPassword", "newPassword", "salt"};

    /**
     * 处理完请求后执行
     */
    @Before("@annotation(controllerLog)")
    public void doBefore(JoinPoint joinPoint, LogOption controllerLog) {
        startTime = System.currentTimeMillis();
    }
    /**
     * 处理完请求后执行
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, LogOption controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, LogOption controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }



    private Log createLog(JoinPoint pjp,LogOption logger){
        Log l = new Log();
        HttpServletRequest request = WebUtil.currentRequest();
        String requestType = request.getHeader("X-Requested-With");
        l.setType("XMLHttpRequest".equals(requestType) ? 1 : 0);
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        String className = pjp.getTarget().getClass().getName();
        String methodName = signature.getName();
        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation lev = method.getAnnotation(ApiOperation.class);
            l.setDescription(lev.value());
        }
        l.setCreateDt(new Date(startTime));
        l.setSpendTime(endTime - startTime);
        l.setLogLevel(logger.value().getValue());
        l.setClassMethod(className + "." + methodName + "()");
        l.setUrl(StringTool.substring(request.getRequestURL().toString(),0,500));
        l.setIp(WebUtil.getIp(request));
        l.setOs(StringTool.substring(WebUtil.getOsInfo(request),0,400));
        l.setBrowser(StringTool.substring(WebUtil.getBrowserInfo(request),0,400));
        l.setMethod(request.getMethod());

        return l;
    }

    private User findUser(Object jsonObject){
        User user = null;
        if(jsonObject instanceof RS){
            RS rs = (RS) jsonObject;
            Object data = rs.get("data");
            if(data instanceof User){
                return (User) data;
            }
            if(data instanceof LoginResult){
                return ((LoginResult) data).getUserInfo();
            }
        }

        return user;
    }

    private boolean isSaveLog(LogOption controllerLog){
        int value = controllerLog.value().value;
        return SystemConfig.getInstance().getLogLevel().contains(value);
    }

    protected void handleLog(final JoinPoint joinPoint, LogOption controllerLog, final Exception e, Object jsonResult) {
        endTime = System.currentTimeMillis();
        if(isSaveLog(controllerLog)){
            try {
                // 获取当前的用户
                LoginUser loginUser = SessionUtil.getCurrentUserSafe();
                User user ;
                if(loginUser == null){
                    user = findUser(jsonResult);
                }else{
                    user = loginUser.getUser();
                }
                //设置日志参数
                Log operatorLog = this.createLog(joinPoint,controllerLog);
                if (user != null) {
                    operatorLog.setUserId(user.getUserId());
                    operatorLog.setUsername(user.getRealName());
                }
                operatorLog.setStatus(ExceptionUtil.getExceptionName(e));
                if (e != null) {
                    operatorLog.setErrorMsg(StringTool.substring(e.getMessage(), 0, 2000));
                }
                //是否保存请求参数
                if(controllerLog.parameter()){
                    this.setRequestParam(joinPoint,controllerLog,operatorLog);
                }
                // 是否保存响应
                if (controllerLog.response() && jsonResult != null) {
                    PropertyExcludeFilter filter = excludePropertyPreFilter(controllerLog.excludeResponse());
                    operatorLog.setResponse(StringTool.substring(JSON.toJSONString(jsonResult,filter), 0, 2000));
                }
                this.handleLoginLog(controllerLog,operatorLog,jsonResult);
                // 保存数据库
                ThreadPoolManager.saveLog(operatorLog);
            } catch (Exception exp) {
                // 记录本地异常日志
                log.error("异常信息:{}", exp.getMessage());
            }
        }

    }

    private void handleLoginLog(LogOption controllerLog, Log l, Object jsonResult){
        if(LogLevel.LOGIN == controllerLog.value() && jsonResult != null){
            RS rs = (RS) jsonResult;
            if(!rs.isSuccess()){
                l.setStatus("Login");
            }
        }
    }

    private void setRequestParam(JoinPoint pjp,LogOption controllerLog,Log operLog){
        HttpServletRequest request = WebUtil.currentRequest();
        String contentType = StringTool.safeToString(request.getHeader("Content-Type"),"").toLowerCase();
        if(contentType.contains("application/json")){
            String params = argsArrayToString(pjp.getArgs(),controllerLog);
            operLog.setParameter(StringTool.substring(params, 0, 2000));
        }else{
            Map<String, Object> paramsMap = WebUtil.getParameterMap(request);
            PropertyExcludeFilter filter = excludePropertyPreFilter(controllerLog.exclude());
            operLog.setParameter(StringTool.substring(JSON.toJSONString(paramsMap, filter), 0, 2000));
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray,LogOption controllerLog) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (ObjectUtil.isNotEmpty(o) && !isFilterObject(o)) {
                    try {
                        String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter(controllerLog.exclude()));
                        params.append(jsonObj).append(" ");
                    } catch (Exception e) {
                        //ignore
                    }
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 忽略敏感属性
     */
    public PropertyExcludeFilter excludePropertyPreFilter(String [] exc) {
        PropertyExcludeFilter filter = new PropertyExcludeFilter();
        if(exc != null && exc.length > 0){
            filter.addExcludes(exc);
        }
        return filter.addExcludes(EXCLUDE_PARAMETERS);
    }
    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        }
        else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        }
        else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }
}
